import { addCart, getCart, setCartItem, deleteCartItem, setCartNumber } from '_api'
import { Toast, Dialog } from 'vant'
export default {
  namespaced: true,
  state: {
    items: [],
    number: 0,
    price: 0
  },
  mutations: {
    // 初始数据
    INIT_CART (state, { items, number, price }) {
      state.items = items
      state.number = number
      state.price = price
    }
  },
  actions: {
    // 修改数量
    SET_CART_NUMBER ({ commit }, params = {}) {
      setCartNumber(params).then((res) => {
        if (res.data.code === 0) {
          commit('INIT_CART', {
            items: res.data.data.items,
            number: res.data.data.number,
            price: res.data.data.price
          })
        }
      })
    },
    // 删除购物车数据
    DELETE_CART_ITEM ({ commit }, params = {}) {
      Dialog.confirm({
        title: '删除数据',
        message: '您确定删除此条数据？'
      })
        .then(() => {
          deleteCartItem(params).then((res) => {
            if (res.data.code === 0) {
              commit('INIT_CART', {
                items: res.data.data.items,
                number: res.data.data.number,
                price: res.data.data.price
              })
            }
            if (res.data.code === 700) {
              commit('INIT_CART', {
                items: [],
                number: 0,
                price: 0
              })
            }
          })
        })
        .catch(() => {
          console.log('拉倒吧')
        })
    },
    // 更改购物车选中
    SET_CART_ITEM ({ commit }, params = {}) {
      setCartItem(params).then((res) => {
        if (res.data.code === 0) {
          commit('INIT_CART', {
            items: res.data.data.items,
            number: res.data.data.number,
            price: res.data.data.price
          }
          )
        }
      })
    },
    // 购物车初始数据
    INIT_CART_INFO ({ commit }, params = {}) {
      getCart(params).then((res) => {
        if (res.data.code === 0) {
          console.log(res)
          commit('INIT_CART', {
            items: res.data.data.items,
            number: res.data.data.number,
            price: res.data.data.price
          }
          )
        }
      })
    },
    // 加购
    ADD_CART ({ commit }, params = {}) {
      addCart(params).then((res) => {
        if (res.data.code === 0) {
          Toast('加入购物车成功')
          console.log(commit)
          commit('INIT_CART', {
            items: res.data.data.items,
            number: res.data.data.number,
            price: res.data.data.price
          }
          )
        }
      })
    }
  }
}
